package com.eagle.epay.thread;

import lombok.Data;
import lombok.ToString;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

@Data
@ToString
public class Shop {
	String name;

	public Shop() {}

	public Shop(String name) {
		this.name = name;
	}

	public double getPrice(String product)  {
		//查询商品的数据库，或链接其他外部服务获取折扣
		try {
			Thread.sleep(4000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("call getPrice..");
		return new Random().nextDouble() * product.charAt(0) + product.charAt(1);
	}

	public Future<Double> getPriceAsync(String product){
		//创建CompletableFuture对象
		CompletableFuture<Double> futurePrice = new CompletableFuture<>();
		new Thread(() ->{
			double price = this.getPrice(product);
			futurePrice.complete(price);
		}).start();
		return futurePrice;
	}

	public CompletableFuture<Double> getPriceAsync2(String product) {
		return CompletableFuture.supplyAsync(() -> this.getPrice(product));
	}
}
